package com.raos.caffeine.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * Spring工具类
 *
 * @author raos
 * @email 991207823@qq.com
 */
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /***
     * 依据配置名或配置信息
     * @param envName 环境配置名
     * @return
     */
    public static String getEnv(String envName) {
        Environment env = getApplicationContext().getEnvironment();
        return env.getProperty(envName);
    }

    /***
     * 获取spring配置文件启用的生效配置名
     * @return
     */
    public static String getProfile() {
        Environment env = getApplicationContext().getEnvironment();
        String[] profile = env.getActiveProfiles();
        if (!ObjectUtils.isEmpty(profile)) {
            return profile[0];
        }
        return "";
    }

}
